<?php


namespace app\repository\Device;


use app\Enums\CardStatus;
use app\Enums\LogChannel;
use App\Enums\UserRole;
use app\model\ApiUser;
use app\model\Card;
use app\model\Games;
use app\model\GamesCard;
use app\model\GamesRecord;
use app\model\Order;
use app\model\OrderCard;
use app\model\Production;
use app\model\RoomDevice;
use app\model\WxUser;
use app\repository\Repository;
use app\Server\PushServer;
use app\Server\TcpServer;
use Carbon\Carbon;
use support\Cache;
use support\Redis;

class DeviceRepository extends Repository
{



    public function handleUdpScan($data)
    {
        dump("到这里了111");
        //判断是否是场内设备
        $device = RoomDevice::query()->where("udp_ip", $data['ip'])->first();
        if (!$device){
            dump("不是我们的设备",$data);
            return $this->ok("",300);
        }
        $card = Card::query()->where("card_no", $data['code'])->first();
        //判断前台设备还是房间设备
        if ($device->is_admin){
            dump("前台设备");
            //前台设备
            $collection = ApiUser::query()->where("role", UserRole::BOSS)->get();
            //前台设备
            //推送数据给前台账号
            foreach ($collection as $item){
                $this->getPushServer()->send($item->username,"udp_scan",$data['code']);
            }

            return $this->success([],"",300);
        }
        $roomUser = ApiUser::query()->where("room_id", $device->id)->first();

        if(!$card){
            dump("没有找到手环");
            if ($roomUser){
                $this->getPushServer()->send($roomUser->username,"udp_scan",$data['code'],"该手环不在系统中，请联系工作人员",400);
            }
            return $this->ok("",300);
        }

        dump("不是前台设备");
        $orderCard = OrderCard::query()->with(['order',"user"])
            ->whereBetween("created_at", [Carbon::now()->startOfDay()->toDateTimeString(), Carbon::now()->endOfDay()->toDateTimeString()])
            ->orderByDesc("created_at")
            ->where([
            "card_id" => $card->id,
            "status" => 1
        ])->first();
        if (!$orderCard){
            dump("没有找到订单");
            if ($roomUser){
                $this->getPushServer()->send($roomUser->username,"udp_scan",$data['code'],"系统数据错误，没有找到您绑定的订单，请联系工作人员",400);
            }
            return $this->success([],"",300);
        }
        //没有找到手环
        $collection1 = GamesCard::query()
            ->where("order_card_id", $orderCard->id)
            ->where(
                "begin_time", "!=", 'null'
            )
            ->where("end_time", "!=", "null")
            ->get();
        $userMini = 0;
        foreach ($collection1 as $item){
            $diff_in_minutes = Carbon::parse($item->begin_time)->diffInMinutes(Carbon::parse($item->end_time));
            $userMini = $userMini + $diff_in_minutes;
        }

        if ($orderCard->order->production_time < $userMini){
            dump('您的手环使用时长已经用完');
            $this->getPushServer()->send($roomUser->username,"udp_scan",[],"您的手环使用时长已经用完",400);
            return $this->success([],'您的手环使用时长已经用完');
        }
        //用户剩余时间
        $userOwnTime = $orderCard->order->production_time - $userMini;
        try {
            $ip = $data["ip"];
            $var = Cache::get("$ip-bind");
            if ($var){
                $gameItem = json_decode($var, true);
                $list = $gameItem['list'];
                $extis = false;
                foreach ($list as $item){
                    if ($item["user_id"] == $orderCard->user->id){
                        $extis = true;
                    }
                }
                if (!$extis){
                    array_push($list,[
                        "user_id"=>$orderCard->user->id,
                        "room_id"=>$device->id,
                        "card_id"=>$card->id,
                        "own_time"=>$userOwnTime,
                        "order_card_id"=>$orderCard->id
                    ]);
                }
                $gameItem['list'] = $list;
                $gameItem["created_at"] = Carbon::now()->getTimestamp();
                $userIdList  = array_column($list, "user_id");
                $userList = WxUser::query()->whereIn("id", $userIdList)->get();
                $gameList = $gameItem["list"];
                $array_column = array_column($gameList, null, "user_id");
                foreach ($userList as &$item){
                    $item->own_time = $array_column[$item->id]["own_time"];
                }
                dump("返回的数据",$userList->toArray());
                if ($roomUser){
                    $this->getPushServer()->send($roomUser->username,"udp_scan",$userList->toArray(),"",200);
                }
            }else{
                $gameItem["list"][] = [
                    "user_id"=>$orderCard->user->id,
                    "room_id"=>$device->id,
                    "card_id"=>$card->id,
                    "own_time"=>$userOwnTime,
                    "order_card_id"=>$orderCard->id

                ];
                $gameItem["created_at"] = Carbon::now()->getTimestamp();
                $userList = WxUser::query()->where("id", $orderCard->user->id)->get();
                $gameList = $gameItem["list"];
                $array_column = array_column($gameList, null, "user_id");
                foreach ($userList as &$item){
                    $item->own_time = $array_column[$item->id]["own_time"];
                }
                dump("返回的数据",$userList->toArray());


                if ($roomUser){
                    $this->getPushServer()->send($roomUser->username,"udp_scan",$userList->toArray(),"",200,true);
                }
            }
            dump('走到最后了');
            Cache::set("$ip-bind",json_encode($gameItem),120);
            return $this->success([
                "key"=>$device->tcp_key,
                "light"=>count($gameItem['list'])
            ],"",201);
        }catch (\Exception $exception){
            dump($exception->getMessage());
            dump($exception->getTraceAsString());
            dump('走到最后了-catch');

            $this->createLogs(LogChannel::UDP_SCAN,
                json_encode([
                    $data
                ]),
                $exception->getMessage(),
                $exception->getTraceAsString()
            );
            return $this->success([],"",201);
        }
        //房间设备
        //新建队伍，并进入缓存
        dump('走到最后了出了 catch');

        return $this->success([],"",201);

        //返回队伍数据给房间外屏



    }


    public function check_key($key,$type)
    {
        if ($type == "game"){
            $model = RoomDevice::query()->where("game_key", $key)->first();
        }else{
            $model = RoomDevice::query()->where("tcp_key", $key)->first();
        }
        if($model){
            return $this->success($model->tcp_ip);
        }
        return $this->error("");
    }

    public function use_score($data)
    {
        try {
            $game = Games::query()->whereBetween("created_at", [Carbon::now()->startOfDay()->toDateTimeString(), Carbon::now()->endOfDay()->toDateTimeString()])
                ->where("device_id", $data["card_no"])
                ->first();
            if (!$game){
                $this->createLogs(LogChannel:: RECEIVE_USER_SCORE,$data,"没有查询到 game","");
                return $this->ok();
            }
            GamesRecord::query()->create([
                "device_id"=>$data["card_no"],
                "game_id"=>$game->id,
                "city_no"=>$data['city_no'],
                "site_no"=>$data['site_no'],
                "vene_no"=>$data['vene_no'],
                "type_no"=>$data['type_no'],
                "project_no"=>$data['project_no'],
                "project_level"=>$data['project_level'],
                "timestamp"=>$data['timestamp'],
                "life"=>$data['life'],
                "game_time"=>$data['time'],
                "score"=>$data['score'],
                "is_promotion"=>$data['is_promotion'],
            ]);
            return $this->ok();
        }catch ( \Exception $exception){
            dump($exception->getTraceAsString());
            dump($exception->getMessage());
        }
    }

    public function handleBeginAction($key, $cardNo, $action)
    {
        try {
            dump("请求了接口");
            $room = RoomDevice::query()->where("game_key", $key)->first();
            $roomUser = ApiUser::query()->where("room_id", $room->id)->first();
            dump("参数",$key,$cardNo,$action);

            if (!$room){
                dump("没有找到这个设备");
                $this->createLogs( LogChannel::RECEIVE_USER_ACTION,json_encode([
                    "key"=>$key,
                    "card_no"=>$cardNo,
                    "action"=>$action
                ]),"没有找到该设备","");
            }
            $game = Games::query()->with(["card"])
                ->whereBetween("created_at", [Carbon::now()->startOfDay()->toDateTimeString(), Carbon::now()->endOfDay()->toDateTimeString()])
                ->where("device_id", $cardNo)->first();
            if (!$game){
                $this->createLogs( LogChannel::RECEIVE_USER_ACTION,json_encode([
                    "key"=>$key,
                    "card_no"=>$cardNo,
                    "action"=>$action
                ]),"找不到该游戏记录 game","");
                dump("找不到游戏记录");
                return $this->ok();
            }
            switch ($action)
            {
                case "01":
                    //用户开始游戏
                    dump("到这里了12312");
                    return $this->success($room->tcp_key);
                    break;
                case "02":
                    //用户停止游戏
                    dump("到这里了123333");
                    //todo 开门
                    $endTime = Carbon::now();
                    $game->end_time = $endTime->toDateTimeString();
                    $game->use_time =Carbon::parse($game->begin_time)->diffInSeconds($endTime);
                    GamesCard::query()->where("game_id",$game->id)->update([
                        "end_time"=>$endTime->toDateTimeString(),
                    ]);
                    if ($roomUser){
                        $this->getPushServer()->send($roomUser->username,"action",$action);
                    }
                    $game->save();
                    return $this->success($room->tcp_key);
                    break;
                case "03":
                    dump("到这里了1112212");
                    //用户在规定时间没有开始游戏
                    $endTime = Carbon::now();
                    $game->end_time = $endTime->toDateTimeString();
                    $game->use_time =Carbon::parse($game->begin_time)->diffInSeconds($endTime);
                    GamesCard::query()->where("game_id",$game->id)->update([
                        "end_time"=>$endTime->getTimestamp(),
                    ]);
                    if ($roomUser){
                        dump("到这里了");
                        $this->getPushServer()->send($roomUser->username,"action",$action);
                    }
                    $game->save();
                    break;
            }
        }catch (\Exception $exception){
            dump($exception->getMessage());
            dump($exception->getTraceAsString());
        }

        return $this->ok();
    }



}